<?php

namespace app\company\controller;

use app\company\validate\CompanyUserValidate;
use app\service\traits\Crud;
use app\company\model\CompanyUser as CompanyUserModel;
use app\company\model\CompanyRole;

class CompanyUser extends Base
{
    private CompanyUserModel $model;

    use Crud;

    public function initialize()
    {
        parent::initialize();
        $this->model            = new CompanyUserModel();
        $this->validateClass    = CompanyUserValidate::class;
        $this->withSearch       = 'user_name,mobile,real_name,status,id,identity';
        $this->isGs             = true;
        $this->checkUniqueField = ['user_name'];
        $this->append           = 'identity_supplier_text';
    }

    public function format($list): mixed
    {
        return $list->each(function ($item) {
            $roleIds          = $item->companyUserRoles()->column('company_role_id');
            $arr              = CompanyRole::whereIn('id', $roleIds)->field('id,name')->select();
            $item->role_names = implode('/', array_column($arr->toArray(), 'name'));
            $item->role_ids   = implode(',', array_column($arr->toArray(), 'id'));
        });
    }
}